package com.ethan.erouter_core;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ERouter {
    Map<String, String> routerMap = new HashMap<>();

    private static volatile ERouter instance = null;

    public static ERouter getInstance() {
        if (instance == null) {
            synchronized (ERouter.class) {
                if (instance == null) {
                    instance = new ERouter();
                }
            }
        }
        return instance;
    }

    public void init(Application application){
        Set<String> stringSet = ClassUntils.getAllClassName(application);
        for(String tmp:stringSet){
            try {
                Class cls = Class.forName(tmp);
                if (IERouter.class.isAssignableFrom(cls)){
                    IERouter ieRouter  = (IERouter) cls.newInstance();
                    ieRouter.loadPath(routerMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
    public void rigister(String path, String cls) {
        routerMap.put(path, cls);
    }
    public void switchTo(Activity activity,String path){
        String cls = routerMap.get(path);
        if (cls!=null){
            Intent intent = new Intent();
            try {
                intent.setClass(activity,Class.forName(cls));
                activity.startActivity(intent);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        }

    }
}
